<?php

class models_oms {

    private $_cache;

    public function __construct($cache) {
        $this->_cache = $cache;
    }

    public function get_stock($sku) {
   
        $config = include ROOT_CONFIG;

        if ($this->_cache->cache('stock_' . $sku)) {
            return $this->_cache->cache('stock_' . $sku);
        } else {
            $sign = md5($sku . API_KEY);
            $country = global_vars::instance()->get('local_db');
            $url = $config['oms_api']['get_stock_api_link'] . "?sku={$sku}&country={$country}&sign={$sign}";
            $resource = curl_init();
            curl_setopt($resource, CURLOPT_URL, $url);
            curl_setopt($resource, CURLOPT_RETURNTRANSFER, 1);
            $store = curl_exec($resource);
            
            if (!isset($store))
                throw new Exception('cannot connect to service');

            $arr_json = json_decode($store, true);
            if ($arr_json) {
                if ($arr_json['error'] === 0) {
                    $this->_cache->cache('stock_' . $sku, $arr_json['data']);
                    return $arr_json['data'];
                } else if ($arr_json['error'] === 2) {
                    throw new PDOException('sku_dose_not_exist');
                }else{
                    throw new Exception('service is error');
                }
            }
            else
                throw new PDOException('sku_dose_not_exist');
        }
    }

}

?>
